package com.greate.community.filter;

import cn.hutool.extra.servlet.ServletUtil;
import com.greate.community.entity.User;
import com.greate.community.entity.VisitData;
import com.greate.community.jwt.JwtTokenUtil;
import com.greate.community.jwt.JwtUser;
import com.greate.community.service.UserService;
import com.greate.community.service.VisitDataService;
import com.greate.community.util.RedisKeyUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

/**
 * 类名称：AuthenticationTokenFilter
 * 类描述：认证拦截器
 * 创建人：CSUpipixia
 * 创建时间：2022/1/28 13:43
 *
 * @version v1.0
 */
@Slf4j
@Component
public class AuthenticationTokenFilter extends OncePerRequestFilter {

    private final UserService userService;
    private final JwtTokenUtil jwtTokenUtil;
    private final VisitDataService visitDataService;
    private final RedisTemplate redisTemplate;

    public AuthenticationTokenFilter(VisitDataService visitDataService,
                                     JwtTokenUtil jwtTokenUtil,
                                     RedisTemplate redisTemplate,
                                     UserService userService) {
        this.visitDataService = visitDataService;
        this.jwtTokenUtil = jwtTokenUtil;
        this.redisTemplate = redisTemplate;
        this.userService = userService;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        log.info("request请求地址: path[{}] uri[{}] ip[{}]", request.getServletPath(), request.getRequestURI(), ServletUtil.getClientIP(request));
        // 获取httpServletRequest中的请求头为“Authorization”的 token 值
        String httpHeader = request.getHeader(this.jwtTokenUtil.getTokenHeader());

        // 验证值是否为空且以tokenHead开头
        if (httpHeader != null && httpHeader.startsWith(this.jwtTokenUtil.getTokenHead())) {
            // 截取tokenHead后面的值
            final String authToken = httpHeader.substring(this.jwtTokenUtil.getTokenHead().length());
            log.info("token：{}", authToken);
            // 获取用户账号
            String userId = jwtTokenUtil.getUsernameFromToken(authToken);

            log.info("JwtAuthenticationTokenFilter[doFilterInternal] checking authentication {} ", userId);
            // 验证用户账号是否合法
            if (userId != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                // 根据userId去缓存中查询user数据
                JwtUser user = (JwtUser) redisTemplate.opsForValue().get(RedisKeyUtil.getTokenKey(userId));
                if (user != null && jwtTokenUtil.validateToken(authToken, String.valueOf(user.getId()))) {
                    // 构建用户认证的结果，并存入 SecurityContext, 以便于 Spring Security 进行授权
                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                            user, user.getPassword(), userService.getAuthorities(user.getId())
                    );
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    SecurityContextHolder.setContext(new SecurityContextImpl(authentication));

                    VisitData visitData = new VisitData();
                    visitData.setPath(request.getServletPath());
                    visitData.setIp(ServletUtil.getClientIP(request));
                    visitData.setCreateTime(new Date());
                    visitData.setUserId(user.getId());
                    visitDataService.addVisitData(visitData);
                }
            }
        }

        filterChain.doFilter(request, response);
    }
}
